<?php
require_once 'UserServiceCategoryLink.php';

/**
 *  zend db table
 */
class Application_Model_DbTable_UserServiceCategoryLinks extends Zend_Db_Table_Abstract
{
    protected $_name = 'ap_user_service_category_link';
}


/**
 *  
 */
class UserServiceCategoryLinks extends BaseMapper
{
    protected $_modelName   = 'UserServiceCategoryLink';
    protected $_dbTableName = 'Application_Model_DbTable_UserServiceCategoryLinks';

    /* ================================================================================
        access database
    ================================================================================ */

    /**
     *  add 
     */
    public function addUserServiceCategoryLink( $model )
    {
        return $this->_save( $model, 'add' );
    }

    /**
     *  update 
     */
    public function updateUserServiceCategoryLink( $model )
    {
        return $this->_save( $model, 'update' );
    }

    /**
     *  find many 
     */
    public function findUserServiceCategoryLinks( $userId=null, $serviceKey=null, $serviceId=null, $page=1, $rowCount=BaseMapper::DEFAULT_ROW_COUNT ) 
    {
        $opt = Array(
            'userId'     => $userId,
            'serviceKey' => $serviceKey,
            'serviceId'  => $serviceId,
            '_orderBy'   => ' ordered_pages ASC, user_id DESC ',
            '_page'      => $page,
            '_rowCount'  => $rowCount,
        );
        return $this->_getByQuery($opt);
    }

    /**
     *  get count by "findUserServiceCategoryLinks" method
     */
    public function getNumFindUserServiceCategoryLinks( $userId='', $serviceKey='', $serviceId='' ) 
    {
        $opt = Array(
            'userId'     => $userId,
            'serviceKey' => $serviceKey,
            'serviceId'  => $serviceId,
        );
        return $this->_getByQuery($opt,true);
    }

    /**
     *  get query
     */
    protected function _getByQuery( $opt, $isGetTotal=false )
    {
        $this->_checkOption($opt);
        $opt += Array(
            'userId'               => (isset($opt['userId'])               ? (int) ($opt['userId'])               : NULL ),
            'serviceKey'           => (isset($opt['serviceKey'])           ?       ($opt['serviceKey'])           : NULL ),
            'serviceId'            => (isset($opt['serviceId'])            ? (int) ($opt['serviceId'])            : NULL ),

            '_orderBy'             => (isset($opt['_orderBy'])             ?       ($opt['_orderBy'])             : ' ordered_pages ASC, id DESC ' ),
            '_page'                => (isset($opt['_page'])                ? (int) ($opt['_page'])                : 1 ),
            '_rowCount'            => (isset($opt['_rowCount'])            ? (int) ($opt['_rowCount'])            : BaseMapper::DEFAULT_ROW_COUNT ),
        );

        if( isset($opt['_page']) && $opt['_page']<=1 ) {
            $opt['_page'] = 1;
        }

        $where = Array();
        if(isset( $opt['userId']              )) { $where[] = $this->getDb()->getAdapter()->quoteInto(' user_id = ? '     , $opt['userId']               );  }
        if(isset( $opt['serviceKey']          )) { $where[] = $this->getDb()->getAdapter()->quoteInto(' service_key = ? ' , $opt['serviceKey']           );  }
        if(isset( $opt['serviceId']           )) { $where[] = $this->getDb()->getAdapter()->quoteInto(' service_id = ? '  , $opt['serviceId']            );  }

        // where from array to string
        $whereString = join(' AND ',$where);
        if(!$whereString) {
            $whereString = null;
        }

        // get total
        if( $isGetTotal ) {
            $select = $this->getDb()->select();
            $select->from( $this->getDb(), Array('COUNT(*) AS total') );
            if($whereString) {
                $select->where( $whereString );
            }
            $rows = $this->getDb()->fetchRow($select);
            $row = $rows->toArray();
            return (int) $row['total'];
        }

        if( isset($opt['_orderBy']) ) {
            $opt['_orderBy'] = explode(',',$opt['_orderBy']);
        }

        //
        //echo $whereString;

        //
        if( NULL === $opt['_page'] ) {
            $rowset = $this->getDb()->fetchAll($whereString, $opt['_orderBy']);
        }
        else {
            $offset = ($opt['_page']-1) * $opt['_rowCount'];
            $rowset = $this->getDb()->fetchAll($whereString, $opt['_orderBy'], $opt['_rowCount'], $offset );
        }
        if( !$rowset ) {
            return NULL;
        }

        $models = Array();
        foreach( $rowset as $row ) {
            $models[] = $this->mapRow( $row->toArray() );
        }
        return $models;

    }

    /* ================================================================================
        about model object
    ================================================================================ */

    /**
     *  set mapRow by pure database record
     */
    public function mapRow($row)
    {
        $model = $this->getModel();
        $model->setId           ( $row['id']            );
        $model->setUserId       ( $row['user_id']       );
        $model->setServiceKey   ( $row['service_key']   );
        $model->setServiceId    ( $row['service_id']    );
        $model->setOrderedPages ( $row['ordered_pages'] );
        return $model;
    }

}
